package com.wm.gridimageupload

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.wm.gridimageupload.bean.ImageInfoBean
import com.wm.gridimageupload.util.ImageUtils
import com.wm.gridimageupload.util.PictureSelectUtils

class MainActivity : ComponentActivity() {

    private lateinit var rvRecyclerView: RecyclerView

    private lateinit var adapter: GridImageUpAdapter

    // 列表数据
    private var datas = mutableListOf<ImageInfoBean>()

    private var type: String = ""

    val TYPE_BB = "报备"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
    }

    /**
     * 初始化视图
     */
    private fun initView() {
        rvRecyclerView = findViewById(R.id.rv_recycler)
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        val layoutManager: GridLayoutManager = GridLayoutManager(this,4)
        rvRecyclerView.layoutManager = layoutManager
        adapter = GridImageUpAdapter()
        rvRecyclerView.adapter = adapter

        adapter.setContext(this)

        adapter.setOnAddPicClickListener(object : GridImageUpAdapter.onAddPicClickListener{
            override fun onAddPicClick() {
                type = TYPE_BB
                onPickerClick()
            }

            override fun onDeletePicClick(position: Int) {

            }

        })
    }

    private fun onPickerClick() {
        XXPermissions.with(this)
            .permission(Manifest.permission.READ_MEDIA_IMAGES)
            .request { permissions, all ->
                if (all) {
                    picSelectUtils()
                }
            }
    }

    private fun picSelectUtils() {
        PictureSelectUtils.gallery("从相册选择",this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            // 选择图片的回调
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                val images: ArrayList<LocalMedia> = PictureSelector.obtainSelectorList(data)
                if (type == TYPE_BB) {
                    ImageUtils.filterImage(datas,images,type)
                    adapter.setData(datas)

                }
            }
        }
    }

}
